/** 
 * Project Name:kaka 
 * File Name:ReadUrlUtil.java 
 * Package Name:com.luoran.kaka.utils 
 * Date:2018年12月6日上午10:25:23 
 * Copyright (c) 2018, Luoran, Inc. All Rights Reserved.
 * 
 */
package com.luoran.kaka.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

/** 
 * ClassName: ReadUrlUtil
 * date: 2018年12月6日 上午10:25:23
 * @author ghl 
 * @since JDK 1.8
 */
public class ReadUrlUtil {
	
	/** 
	 * 
	 * @author ghl 2018年12月6日上午10:39:21
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws JSONException 
	 * @since JDK 1.8
	 * readJsonFromUrl:访问接口URL并封装返回值为JSON对象
	 */ 
	public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
		InputStream is = new URL(url).openStream();
		try {
			BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
			StringBuilder sb = new StringBuilder();
			int cp;
			while ((cp = rd.read()) != -1) {
				sb.append((char) cp);
			}
			String jsonText = sb.toString();
			JSONObject json = JSONObject.parseObject(jsonText);
			return json;
		} finally {
			is.close();
		}
	}
}
